/* 
 * @(#) ChangeAction.java  1.0  2004-4-22 
 * 
 * Copyright 2003 by LongTop Corporation. 
 * All rights reserved. 
 * 
 * This software is the confidential and proprietary information of 
 * LongTop Corporation ("Confidential Information").  You 
 * shall not disclose such Confidential Information and shall use 
 * it only in accordance with the terms of the license agreement 
 * you entered into with LongTop. 
 */

package com.cnc.fd.web;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionServlet;
 

import com.cnc.bas.query.PageInfo;
import com.cnc.bas.util.Constants;
import com.cnc.bas.util.LTUtil;
import com.cnc.bas.web.BasMapForm;
import com.cnc.bas.web.SecureBaseDispatchAction;
import com.cnc.fd.CustomerConfig;
import com.cnc.fd.hiber.FdTaskList;
import com.cnc.fd.service.FdDao;
import com.cnc.fd.service.IFdService;
import com.cnc.fd.util.FdProperties;
import com.cnc.fd.util.QueryOpersHelper;
import com.cnc.fd.util.TaskTipUtil;
import com.cnc.ssm.UserInfo;

/**
 * @author LW
 * @version 1.0 
 */
public class TaskAction extends SecureBaseDispatchAction {

    private FdDao fdDao = null;
    private IFdService service = null;
    private static final int defaultPageSize = 15;
    private static final int maxPageSize = 2000;
    
 // 文件同步管理界面自动刷新的时间间隔
    private static final int TASK_SHOW_REFRESH_TIME = FdProperties.getIntProperty("TASK_SHOW_REFRESH_TIME");
    
    public void setServlet(ActionServlet actionServlet) {
        super.setServlet(actionServlet);
        fdDao = (FdDao) this.getBean(FdDao.BEAN_ID);
        service = (IFdService) this.getBean(IFdService.BEAN_ID);
    }
    
    public ActionForward serverQuery(ActionMapping mapping,ActionForm form,HttpServletRequest request,
           HttpServletResponse response) throws Exception {       
        return mapping.findForward("serverQuery");
    }
    
    public ActionForward fsQuery(ActionMapping mapping,ActionForm form,HttpServletRequest request,
           HttpServletResponse response) throws Exception {       
    	return mapping.findForward("fsQuery");
    }
    
    public ActionForward fileQuery(ActionMapping mapping,ActionForm form,HttpServletRequest request,
	           HttpServletResponse response) throws Exception {       
    	UserInfo userInfo = (UserInfo)request.getSession().getAttribute(Constants.USER_KEY);
    	request.setAttribute("loginAccount",userInfo.getUserCode());
    	request.setAttribute("loginType", userInfo.getUserType());
    	
        // 非系统用户下  判断用户是否有可查询用户列表
        if (!userInfo.getUserType().equals(Constants.ACCOUNT_ADMIN)) {
            if (QueryOpersHelper.getInstance().hasQueryOpers(userInfo.getUserCode())) {
                request.setAttribute("hasQueryOpers", true);
                request.setAttribute("queryOpers", QueryOpersHelper.getInstance()
                        .getQueryOpersByOper(userInfo.getUserCode()));
            } else {
                request.setAttribute("hasQueryOpers", false);
            }
        }
    	return mapping.findForward("fileQuery");
    }
    
    
    public ActionForward serverList(ActionMapping mapping, ActionForm form,HttpServletRequest request,
            HttpServletResponse response) throws Exception {
	HashMap hs = ((BasMapForm) form).getHs();
	int intCurrentPage = 1;
	String currPage = request.getParameter("intCurrentPage");
	try{
		intCurrentPage = Integer.parseInt(currPage);
	}
	catch(Exception e){
	}
	
	int intTotalPages = 1;
	String totalPage = request.getParameter("intTotalPages");
	try{
		intTotalPages = Integer.parseInt(totalPage);
	}
	catch(Exception e){
		
	}
	int pageSize = (intTotalPages==-1)?maxPageSize:defaultPageSize;
	PageInfo page = new PageInfo(intCurrentPage,pageSize);
	fdDao.getServerInfo(hs,page);
	LTUtil.setPageData(request,page);
	return mapping.findForward("serverList");
    }
    
    public ActionForward fsManageList(ActionMapping mapping, ActionForm form,HttpServletRequest request,
            HttpServletResponse response) throws Exception {
	HashMap hs = ((BasMapForm) form).getHs();
	HttpSession session = request.getSession();
	UserInfo userInfo = (UserInfo)session.getAttribute(Constants.USER_KEY);
	String loginAccount = userInfo.getUserCode();
	String userType = userInfo.getUserType();
	
	if (!userType.equals(Constants.ACCOUNT_ADMIN)) {
            String customerName = (String) hs.get("customerName");
            if(QueryOpersHelper.getInstance().hasQueryOpers(loginAccount)){
                if(StringUtils.isEmpty(customerName)){
                    hs.put("allQueryOpers", "1"); 
                    hs.put("customerNameList", QueryOpersHelper.getInstance().getQueryOpersByOper(loginAccount));
                 }
                 else {
                     if (!QueryOpersHelper.getInstance().canQuery(
                             userInfo.getUserCode(), customerName)) {
                         // 用户查询的是不在权限范围内的用户，则默认查询自身信息
                         hs.put("customerName", loginAccount);
                     }
                 } 
            }
            else{
                if(StringUtils.isEmpty(customerName)){
                    hs.put("customerName", loginAccount);
                }
            }
            
        }
	int intCurrentPage = 1;
	String currPage = request.getParameter("intCurrentPage");
	try{
		intCurrentPage = Integer.parseInt(currPage);
	}
	catch(Exception e){
	}
	
	int intTotalPages = 1;
	String totalPage = request.getParameter("intTotalPages");
	try{
		intTotalPages = Integer.parseInt(totalPage);
	}
	catch(Exception e){
		
	}
	int pageSize = (intTotalPages==-1)?maxPageSize:defaultPageSize;
	PageInfo page = new PageInfo(intCurrentPage,pageSize);
	fdDao.getSyncFileInfo(hs,page);
	List list = page.getPageData();
	
	boolean flag = false;	
	if(!userType.equals(Constants.ACCOUNT_ADMIN)){	  
	  //判断是否需要过滤数据
	    flag = CustomerConfig.getAllowFailureCount(loginAccount) < 0;
	 
	    // 今天已经同步成功的文件数
	    long todayUploadSyncSuccessCount = fdDao.getTodaySyncSuccessTaskByCustomerAndStatus(loginAccount);
	    
	    // 客户一天可以同步的上传类型的文件数
	    long customerMaxDaySyncCount = CustomerConfig.getAllowDayUploadSyncCount(loginAccount);
	    
	    // 今天还能同步的上传文件个数
	    long todayLeftSyncCount = 0;
	    if(customerMaxDaySyncCount >=0){
	        request.setAttribute("limitSync", true);
	        if(customerMaxDaySyncCount > todayUploadSyncSuccessCount){
	            todayLeftSyncCount = customerMaxDaySyncCount - todayUploadSyncSuccessCount; 
	        }
	        request.setAttribute("dayUploadSyncCount", customerMaxDaySyncCount);
	    }
	    else{
	        request.setAttribute("limitSync", false);
	    }
	      request.setAttribute("todayUploadSyncSuccessCount", todayUploadSyncSuccessCount);
	    request.setAttribute("todayLeftSyncCount", todayLeftSyncCount);
	}
	
	//设置同步进度 
	for(int i = 0;i<list.size();i++){
	    Map map = (Map)list.get(i);
	    String taskId = String.valueOf(map.get("taskId"));
	    String taskStatus = map.get("taskStatus").toString();
	    String taskKind = map.get("taskKind").toString();
	    map.put("taskStatusTip", TaskTipUtil.getTaskStatusTip(taskStatus));
	    map.put("taskKindTip", TaskTipUtil.getTaskKindTip(taskKind));
	    
	    if(map.get("taskKind").equals("md5failure")){
	    	map.put("progress", "0.00");		    
    		continue;
	    }
	    
	    if(taskStatus.equals("success")){
	    	map.put("progress", "100.00");	    	
	    }else if(taskStatus.equals("failure") && flag){
	    	map.put("taskStatus", "success");
			map.put("progress", "100.00");	
	    }else{
	    	Map progressMap = fdDao.getTaskProgress(taskId);
			Object progress = progressMap.get("progress");
			map.put("progress", progress==null ? "0.00" : progress);
	    }	    
	}	
		LTUtil.setPageData(request,page);	
		request.setAttribute("loginAccount", loginAccount);
		request.setAttribute("loginType", userType);
		
		request.setAttribute("startDate", hs.get("startDate"));
	    request.setAttribute("endDate", hs.get("endDate"));
	    request.setAttribute("refreshTime", TASK_SHOW_REFRESH_TIME);
	    
	    // 非系统用户下  判断用户是否有可查询用户列表
	    if (!userType.equals(Constants.ACCOUNT_ADMIN)) {
            if (QueryOpersHelper.getInstance().hasQueryOpers(userInfo.getUserCode())) {
                request.setAttribute("hasQueryOpers", true);
                request.setAttribute("queryOpers", QueryOpersHelper.getInstance()
                        .getQueryOpersByOper(userInfo.getUserCode()));
            } else {
                request.setAttribute("hasQueryOpers", false);
            }
        }
	    
		return mapping.findForward("fsQuery");
    }
    
    public ActionForward deleSyncFile(ActionMapping mapping, ActionForm form,HttpServletRequest request,
            HttpServletResponse response) throws Exception {
	String [] taskIds = request.getParameter("id").split(",");
	//写入操作日志
	HashMap log = new HashMap();
	UserInfo userInfo = (UserInfo) request.getSession().getAttribute(
			Constants.USER_KEY);
	log.put("OPER_CODE", userInfo.getUserCode());
	log.put("OPER_NAME", userInfo.getUserName());
	log.put("ACTION_LOG", "删除了文件同步任务. ");
	 
	fdDao.deleteSyncFileInfo(taskIds);
	return queryAgain(mapping,form,request,response);
    }

    public ActionForward syncFile(ActionMapping mapping, ActionForm form,HttpServletRequest request,
            HttpServletResponse response) throws Exception {
	String [] taskIds = request.getParameter("id").split(",");
	fdDao.updateSyncFileInfo(taskIds);
	//写入操作日志
	HashMap log = new HashMap();
	UserInfo userInfo = (UserInfo) request.getSession().getAttribute(
			Constants.USER_KEY);
	log.put("OPER_CODE", userInfo.getUserCode());
	log.put("OPER_NAME", userInfo.getUserName());
	log.put("ACTION_LOG", "修改了同步任务完成状态." );
	 
	return queryAgain(mapping,form,request,response);
    }
    
    
    public ActionForward syncFileDetailList(ActionMapping mapping, ActionForm form,HttpServletRequest request,
            HttpServletResponse response) throws Exception {
	String taskId = request.getParameter("id");
	HashMap hs = ((BasMapForm) form).getHs();
	int intCurrentPage = 1;
	String currPage = request.getParameter("intCurrentPage");
	try{
		intCurrentPage = Integer.parseInt(currPage);
	}
	catch(Exception e){
	}
	
	int intTotalPages = 1;
	String totalPage = request.getParameter("intTotalPages");
	try{
		intTotalPages = Integer.parseInt(totalPage);
	}
	catch(Exception e){
		
	}
	int pageSize = (intTotalPages==-1)?maxPageSize:defaultPageSize;
	PageInfo page = new PageInfo(intCurrentPage,pageSize);
	fdDao.getSyncFileDetail(taskId,hs,page);
	LTUtil.setPageData(request,page);	
	request.setAttribute("taskId", taskId);
	request.setAttribute("params", request.getParameter("params"));
	return mapping.findForward("fsDetail");
    }

    
    public ActionForward fileQueryList(ActionMapping mapping, ActionForm form,HttpServletRequest request,
            HttpServletResponse response) throws Exception {	
    	HashMap hs = ((BasMapForm) form).getHs();
        UserInfo userInfo = (UserInfo)request.getSession().getAttribute(Constants.USER_KEY);
        String loginAccount = userInfo.getUserCode();
        String userType = userInfo.getUserType();
    	if (!userType.equals(Constants.ACCOUNT_ADMIN)) {
            String customerName = (String) hs.get("customerName");
            if(QueryOpersHelper.getInstance().hasQueryOpers(loginAccount)){
                if(StringUtils.isEmpty(customerName)){
                    hs.put("allQueryOpers", "1"); 
                    hs.put("customerNameList", QueryOpersHelper.getInstance().getQueryOpersByOper(loginAccount));
                 } 
                else {
                    if (!QueryOpersHelper.getInstance().canQuery(
                            userInfo.getUserCode(), customerName)) {
                        // 用户查询的是不在权限范围内的用户，则默认查询自身信息
                        hs.put("customerName", loginAccount);
                    }
                }
            }
            else{
                if(StringUtils.isEmpty(customerName)){
                    hs.put("customerName", loginAccount);
                }
            }
        }
    	
    	int intCurrentPage = 1;
		String currPage = request.getParameter("intCurrentPage");
		try{
			intCurrentPage = Integer.parseInt(currPage);
		}
		catch(Exception e){
		}
		
		int intTotalPages = 1;
		String totalPage = request.getParameter("intTotalPages");
		try{
			intTotalPages = Integer.parseInt(totalPage);
		}
		catch(Exception e){
			
		}
	int pageSize = (intTotalPages==-1)?maxPageSize:defaultPageSize;
	PageInfo page = new PageInfo(intCurrentPage,pageSize);
	fdDao.getFileDetail(hs,page);
	LTUtil.setPageData(request,page);	
	
	return mapping.findForward("fileQueryList");
    }
    
    public ActionForward queryAgain(ActionMapping mapping, ActionForm form,HttpServletRequest request,
            HttpServletResponse response) throws Exception {	
    	
    	HashMap hs = new HashMap();
	hs.put("customerName", request.getParameter("customerName"));
	hs.put("realName", request.getParameter("realName"));
	hs.put("fileName", request.getParameter("fileName"));
	hs.put("taskType", request.getParameter("taskType"));
	hs.put("status", request.getParameter("status"));
	hs.put("sourceIp", request.getParameter("sourceIp"));
	hs.put("startDate", request.getParameter("startDate"));
	hs.put("endDate", request.getParameter("endDate"));
	
	((BasMapForm)form).setHs(hs);
	return this.fsManageList(mapping,form, request, response);
    } 
    
    
  //批量删除更新文件同步任务状态
	public ActionForward batchSyncTask(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		HashMap condition = new HashMap();
		String entername=(String)request.getParameter("customerName");
		String filename=(String)request.getParameter("fileName");
		String taskKind=(String)request.getParameter("taskType");
		String taskStatus=(String)request.getParameter("status");
		String sourceIp=(String)request.getParameter("sourceIp");
		String startDate=(String)request.getParameter("startDate");
		String endDate=(String)request.getParameter("endDate");
		if(StringUtils.isNotEmpty(entername))
			condition.put("entername",entername);
		if(StringUtils.isNotEmpty(taskKind))
			condition.put("taskKind",taskKind);
		if(StringUtils.isNotEmpty(taskStatus))
			condition.put("taskStatus",taskStatus);	
		if(StringUtils.isNotEmpty(filename))
			condition.put("filename",filename);
		if(StringUtils.isNotEmpty(sourceIp))
			condition.put("sourceIp",sourceIp);
		if(StringUtils.isNotEmpty(startDate))
			condition.put("startDate",startDate);
		if(StringUtils.isNotEmpty(endDate))
			condition.put("endDate",endDate);
		String status=(String)request.getParameter("oper");
		// 写入操作日志
		HashMap log = new HashMap();
		UserInfo userInfo = (UserInfo) request.getSession().getAttribute(
				Constants.USER_KEY);
		log.put("OPER_CODE", userInfo.getUserCode());
		log.put("OPER_NAME", userInfo.getUserName());
		log.put("ACTION_LOG", status+": " + condition);
		 
		return queryAgain(mapping, form, request, response);
	}
	
	/**
	 * 重启任务
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward rerun(ActionMapping mapping, ActionForm form,HttpServletRequest request,
            HttpServletResponse response) throws Exception {
    String [] taskIds = request.getParameter("id").split(",");
    fdDao.restartSyncTask(taskIds);
    //写入操作日志
    HashMap log = new HashMap();
    UserInfo userInfo = (UserInfo) request.getSession().getAttribute(
            Constants.USER_KEY);
    log.put("OPER_CODE", userInfo.getUserCode());
    log.put("OPER_NAME", userInfo.getUserName());
    log.put("ACTION_LOG", "重启了任务" );
     
    return queryAgain(mapping,form,request,response);
    }

	/**
	 * 标记状态为运维处理中（给客户一个好的提示）
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward operator(ActionMapping mapping, ActionForm form,HttpServletRequest request,
            HttpServletResponse response) throws Exception {
	String [] taskIds = request.getParameter("id").split(",");
	fdDao.setOperatorTask(taskIds);
	//写入操作日志
	HashMap log = new HashMap();
	UserInfo userInfo = (UserInfo) request.getSession().getAttribute(
			Constants.USER_KEY);
	log.put("OPER_CODE", userInfo.getUserCode());
	log.put("OPER_NAME", userInfo.getUserName());
	log.put("ACTION_LOG", "设置任务状态为“运维处理中”" );
	 
	return queryAgain(mapping,form,request,response);
    }
	
	/**
	 * 显示帮助对话框
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward showHelpDialog(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        String taskId = request.getParameter("id");
        if (taskId != null && !taskId.trim().equals("")) {
            FdTaskList task = fdDao.getTaskById(taskId);
            request.setAttribute("task", task);
            request.setAttribute("taskKindTip", TaskTipUtil.getTaskKindTip(task.getTaskKind()));
            request.setAttribute("taskStatusTip", TaskTipUtil.getTaskStatusTip(task.getTaskStatus()));
        } else {
            request.setAttribute("task", new FdTaskList());
        }

        return mapping.findForward("fsHelp");
    }
}

